package com.heying.xmlandjson.jacksonjson;

import com.heying.xmlandjson.entity.User;

import java.lang.reflect.Field;

public class MyJson {

    public String serialize(Object object) throws Exception {
        StringBuilder s = new StringBuilder("{");
        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            s.append("\"");
            s.append(field.getName());
            s.append("\"");
            s.append(":");
            s.append("\"");
            s.append(field.get(object));
            s.append("\"");
            s.append(",");
        }
        return s.substring(0, s.length()-1)+"}";
    }

    public <T> T deserialize(String json,Class<T> clazz) throws Exception {
        String[] sarr = json.split(",");
        T t = clazz.getConstructor().newInstance();
        for(String s:sarr){
            String[] split = s.split(":");
            String fieldName = split[0].replaceAll("[\",\\{]", "");
            Field field = clazz.getDeclaredField(fieldName);
            String value = split[1].replace("[\",\\}]", "");
            field.setAccessible(true);
            field.set(t,value);
        }
        return t;
    }

    public static void main(String[] args) throws Exception {
        String json = "{\"username\":\"aaa\",\"password\":\"123\"}";
        MyJson myJson = new MyJson();
        User user = myJson.deserialize(json,User.class);
        System.out.println(user);
        System.out.println(myJson.serialize(user));
    }
}
